Page
    ({
        data:
        {
            hasCode: true,
            hotel: {
                logoUrl: 'https://www.baidu.com/img/flexible/logo/pc/result.png',
                appQrcode:'http://thumb10.jfcdns.com/2018-03/bce5ab9ee14102a6.jpeg',
            },
            roomCodeBa: 'http://thumb10.jfcdns.com/2018-03/bce5ab9ee14102a6.jpeg',
            timer: '',
            previous: 0,
        },

        onLoad(options) {

        },

        onShow() {
            wx.showLoading({
                title: '',
                mask: true
            })
            setTimeout(() => {
                wx.hideLoading({
                    success: (res) => { },
                })
            }, 2000)
            this.initi();
        },

        initi() {
            //如果有二维码，就开始画图
            if (1) {
                this.getShareInfoObj().then(res => {
                    this.handleSaveImg().then(() => console.timeEnd("eeee"));
                })
            }
        },

        //获取分享信息和处理图片，图片在取到的时候是不能直接画在图上的，必须要保存到本地然后再去画图
        getShareInfoObj() {
            var hotel = this.data.hotel
            return new Promise((resolve, reject) => {
                console.time("eeee");
                Promise.all([
                    this.downloadFiles(hotel.logoUrl, 'logoUrlTemp'),
                    this.downloadFiles(this.data.roomCodeBa, 'roomCodeBaTemp'),
                    this.downloadFiles(hotel.appQrcode, 'appQrcodeTemp'),
                ]).then(res => {
                    resolve();
                }).catch((error) => {
                    reject();
                });
            })
        },

        downloadFiles(url, param) {
            console.warn('downloadFiles', url, param);
            let self = this;
            return new Promise((resolve, reject) => {
                wx.downloadFile({
                    url: url,
                    success(res) {
                        if (res.statusCode == 200) {
                            let data = {};
                            data[param] = res.tempFilePath;
                            self.setData(data);
                            resolve();
                        } else {
                            reject();
                        }
                    },
                    fail(res) {
                        console.warn('downloadFiles', param, res);
                        //报错信息：downloadFile:fail url not in domain list，原因：图片的地址是http，调试模式，不校验域名可以下载，正式环境报错
                        //fail的错误日志需要打印，便于排查问题
                        console.warn('saveImageToPhotosAlbum-res', res);
                        reject();
                    },
                })
            })
        },

        //图片下载到微信本地临时文件目录，开始画图
        handleSaveImg() {
            let self = this;
            return new Promise((resolve, reject) => {
                let systemInfo = wx.getSystemInfoSync();
                let windowWidth = systemInfo.windowWidth;
                let windowHeight = systemInfo.windowHeight;
                //根据iphone6基准的宽度，进行px设备适配
                let unit = systemInfo.windowWidth / 375;
                // 创建画布对象
                const ctx = wx.createCanvasContext("myCanvas", self);
                ctx.setFillStyle('#fff')
                ctx.fillRect(0, 0, 375 * unit, 112 * unit); //画矩形
                ctx.drawImage(self.data.logoUrlTemp, 70 * unit, 26 * unit, 66 * unit, 66 * unit)    //  画头像icon
                ctx.font = 'normal bold 20px PingFang SC'
                ctx.setFillStyle('#333333')   //  颜色
                ctx.setTextAlign('center')
                var name = "阿根高级大酒店（五一店）";
                // var name = self.data.hotel.name;
                //根据括号进行换行
                if (name.indexOf('（') != -1 || name.indexOf('(') != -1) {
                    var index = name.indexOf('（') != -1 ? name.indexOf('（') : name.indexOf('(');
                    var line1 = name.substring(0, index);
                    var line2 = name.substring(index);
                    ctx.fillText(line1, windowWidth / 2 + unit * 20, unit * 50, unit * 220)    // 第一行
                    ctx.fillText(line2, windowWidth / 2 + unit * 20, unit * (50 + 30), unit * 220)    // 第二行 
                }
                //换行居中适配
                else if (name.length > 9) {
                    var line1 = name.substring(0, 9);
                    var line2 = name.substring(9);
                    ctx.fillText(line1, windowWidth / 2 + unit * 20, unit * 50, unit * 220)    // 第一行
                    ctx.fillText(line2, windowWidth / 2 + unit * 20, unit * (50 + 30), unit * 220)    // 第二行
                } else {
                    ctx.fillText(name, windowWidth / 2 + unit * 20, unit * 50 + 16, unit * 220)    // 写昵称和位置
                }
                ctx.setFillStyle('#1B74FF')
                ctx.fillRect(0, 112 * unit, windowWidth, 451 * unit); //画下面的矩形，背景图代替资源图片显示
                // ctx.drawImage(self.data.roomCodeBaTemp, 0, 112 * unit, windowWidth, 451 * unit)    //  画背景图
                ctx.drawImage(self.data.appQrcodeTemp, 65 * unit, 166 * unit, 244 * unit, 244 * unit)    //  画二维码

                //把画板内容绘制成图片，并回调 画板图片路径
                ctx.draw(false, () => {
                    wx.canvasToTempFilePath({
                        x: 0,
                        y: 0,
                        width: windowWidth,
                        height: windowHeight,
                        destWidth: unit * 3750, // 设置大一点清晰度会高
                        destHeight: unit * 5600,
                        canvasId: 'myCanvas',
                        success(res) {
                            console.log('canvasToTempFilePathRes', res);
                            self.setData({
                                shareImgPath: res.tempFilePath,
                            })
                            resolve();
                        },
                        fail(res) {
                            console.log('canvasToTempFilePathResFail', res);
                            reject();
                        },
                    })
                })
            });
        },

        //函数节流_时间戳实现_避免3s内重复下载图片
        commitTamp() {
            var previous = this.data.previous;
            var now = new Date();
            if (now - previous > 3000) {
                this.saveImageToPhoto();
            } else {
                wx.showToast({
                    title: '图片下载中，请稍后再试',
                    icon: 'none',
                })
            }
            this.data.previous = now;
        },

        //  点击按钮canvas图片的时候保存图片
        saveImageToPhoto() {
            wx.showLoading({
                title: '保存中...',
                mask: true
            })
            console.warn('this.data.shareImgPath', this.data.shareImgPath);
            if (!this.data.hotel.logoUrl) {
                wx.showLoading({
                    title: '当前酒店未上传酒店logo',
                    mask: true
                })
            }
            // 防抖-在事件被触发1.5秒后再执行回调，如果在这1.5秒内又被触发，则重新计时。
            else if (!this.data.shareImgPath) {
                var timer = this.data.timer;
                clearTimeout(timer);
                timer = setTimeout(() => {
                    this.wxgetSetting();
                }, 1500)
            }
            else {
                this.wxgetSetting();
            }
        },

        //保存canvas生成的图片到相册
        wxgetSetting() {
            let self = this;
            //（1）获取用户授权的信息
            wx.getSetting({
                success(res) {
                    console.warn('getSetting', res);
                    //判断scope.writePhotosAlbum的值，若为true则已经授权，直接调用保存到相册的方法；
                    if (res.authSetting['scope.writePhotosAlbum']) {
                        self.saveImageToPhotosAlbum();
                        //若为undefined，则说明是第一次授权，需要调用wx.authorize弹出授权框，授权框只在第一次询问时弹出，如果用户已经拒绝了，则不会弹出。
                    } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
                        wx.authorize({
                            scope: 'scope.writePhotosAlbum',
                            success() {
                                self.saveImageToPhotosAlbum();
                            },
                            fail(res) {
                                console.warn('authorize-fail', res);
                                wx.hideLoading();
                            }
                        })
                    } else {
                        wx.hideLoading();
                        //若为false,则已经拒绝了授权，这时候我们需要调用wx.openSetting引导用户打开设置，保存到相册
                        //wx.openSetting,打开小程序设置页,避免此类滥用情况，微信调整了开启方式，button和对话框Modad确认按钮调用wx.openSetting有效
                        wx.showModal({
                            title: "温馨提示",
                            content: '您没有开启保存相册开关，请点击设置按钮打开',
                            confirmText: '去设置',
                            cancelText: '取消',
                            success(res) {
                                if (res.confirm) {
                                    wx.openSetting({
                                        success(res) {
                                            if (res.authSetting['scope.writePhotosAlbum']) {
                                                self.saveImageToPhotosAlbum();
                                            } else {
                                                wx.showToast({
                                                    title: '您没有开启保存相册开关，无法保存到相册',
                                                    icon: 'none'
                                                })
                                            }
                                        },
                                    })
                                }
                            },
                        })
                    }
                }
            })

        },

        //画板路径保存成功后，调用方法吧图片保存到用户相册
        saveImageToPhotosAlbum() {
            let self = this;
            console.warn('saveImageToPhotosAlbum调用次数统计');
            return new Promise((resolve, reject) => {
                wx.saveImageToPhotosAlbum({
                    filePath: self.data.shareImgPath,
                    success(res) {
                        wx.showToast({
                            title: '已保存',
                            icon: 'none',
                            duration: 2000,
                        })
                        resolve();
                    },
                    fail(res) {
                        console.warn('saveImageToPhotosAlbum-res', res);
                        //技巧1：当错误信息toast无法捕捉，使用弹窗展示
                        // wx.showModal({
                        //     title: '保存异常',
                        //     content: JSON.stringify(res),
                        //     success(res) {
                        //         if (res.confirm) {
                        //         }
                        //     },
                        // })
                        //技巧2：加强展示时间
                        wx.showToast({
                            title: '保存失败' + res.errMsg,
                            icon: 'none',
                            duration: 2000,
                        })
                        reject();
                    },
                    complete(res) {
                        wx.hideLoading({
                            success: (res) => { },
                        })
                    }
                })
            })
        },

    });